﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.IO;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;


/// <summary>
///Toolkit 的摘要说明
/// </summary>
public class Toolkit
{
    private static string PreviousUUID = null;

    public Toolkit()
    {
    }

    public static string TopicIdOfTrainMaterial
    {
        get
        {
            return GetSettingValue("TopicIdOfTrainMaterial").Value;
        }
    }
    public static string TopicIdOfTrainReview
    {
        get
        {
            return GetSettingValue("TopicIdOfTrainReview").Value;
        }
    }
    public static string ArticlePrefixOfTrain
    {
        get
        {
            return GetSettingValue("ArticlePrefixOfTrain").Value;
        }
    }
    public static string ArticlePrefixOfReview
    {
        get
        {
            return GetSettingValue("ArticlePrefixOfReview").Value;
        }
    }
    public static string TemplateOfTrainArticle
    {
        get
        {
            return GetSettingValue("TemplateOfTrainArticle").Value;
        }
    }
    public static string TemplateOfStatTrain
    {
        get
        {
            return GetSettingValue("TemplateOfStatTrain").Value;
        }
    }
    public static string TemplateOfStatArticleDetail
    {
        get
        {
            return GetSettingValue("TemplateOfStatArticleDetail").Value;
        }
    }
    public static string TemplateOfStatArticleAll
    {
        get
        {
            return GetSettingValue("TemplateOfStatArticleAll").Value;
        }
    }
    public static string TemplateOfStatTeacherAll
    {
        get
        {
            return GetSettingValue("TemplateOfStatTeacherAll").Value;
        }
    }
    public static string TemplateOfStatQuestionAll
    {
        get
        {
            return GetSettingValue("TemplateOfStatQuestionAll").Value;
        }
    }
    public static string TemplateOfStatQuestionDetail
    {
        get
        {
            return GetSettingValue("TemplateOfStatQuestionDetail").Value;
        }
    }
    public static string TemplateOfStatTeacherDetail
    {
        get
        {
            return GetSettingValue("TemplateOfStatTeacherDetail").Value;
        }
    }
    public static string PathOfArticle
    {
        get
        {
            return GetSettingValue("PathOfArticle").Value;
        }
    }
    public static string InitialPassword
    {
        get
        {
            return GetSettingValue("InitialPassword").Value;
        }
    }
    public static string PathOfReport
    {
        get
        {
            return GetSettingValue("PathOfReport").Value;
        }
    }
    public static string PathOfUpload
    {
        get
        {
            return GetSettingValue("PathOfUpload").Value;
        }
    }
    public static string PathOfExportTrains
    {
        get
        {
            return GetSettingValue("PathOfExportTrains").Value;
        }
    }
    public static string PathOfAdminExportTrains
    {
        get
        {
            return GetSettingValue("PathOfAdminExportTrains").Value;
        }
    }
    public static string PathOfTemplates
    {
        get
        {
            return GetSettingValue("PathOfTemplates").Value;
        }
    }
    public static string PathOfExportJoined
    {
        get
        {
            return GetSettingValue("PathOfExportJoined").Value;
        }
    }
    public static string PathOfTemporary
    {
        get
        {
            return GetSettingValue("PathOfTemporary").Value;
        }
    }
    public static string ApplicationRoot
    {
        get
        {
            string root = HttpContext.Current.Request.ApplicationPath;
            if (root == "/")
            {
                root = "";
            }
            return root;
        }
    }
    public static int PageSize
    {
        get
        {
            Setting s = GetSettingValue("PageSize");
            if (s == null)
            {
                return 10;
            }
            else
            {
                return Convert.ToInt32(s.Value);
            }
        }
    }
    public static string NextUUID
    {
        get
        {
            long time;
            string nu;

            do
            {
                time = DateTime.Now.Ticks;
                nu = Convert.ToString(time, 16);
            } while (nu == PreviousUUID);

            PreviousUUID = nu;

            return PreviousUUID;
        }
    }
    public static string CurrentUserDistrict
    {
        get
        {
            if (HttpContext.Current.Session["District"] == null || Convert.ToString(HttpContext.Current.Session["District"]) == "")
            {
                throw new Exception("所属县区为空！");
            }
            else
            {
                return Convert.ToString(HttpContext.Current.Session["District"]);
            }
        }
    }
    public static string CurrentUserBelong
    {
        get
        {
            if (HttpContext.Current.Session["Belong"] == null || Convert.ToString(HttpContext.Current.Session["Belong"]) == "")
            {
                throw new Exception("所属单位为空！");
            }
            else
            {
                return Convert.ToString(HttpContext.Current.Session["Belong"]);
            }
        }
    }
    public static string CurrentUserID
    {
        get
        {
            if (HttpContext.Current.Session["ManagerID"] == null)
            {
                return "";
            }
            else
            {
                return Convert.ToString(HttpContext.Current.Session["ManagerID"]);
            }
        }
    }
    public static string CurrentUserName
    {
        get
        {
            if (HttpContext.Current.Session["ManagerName"] == null)
            {
                return "";
            }
            else
            {
                return Convert.ToString(HttpContext.Current.Session["ManagerName"]);
            }
        }
    }
    public static string CurrentTeacherID
    {
        get
        {
            if (HttpContext.Current.Session["TeacherID"] == null)
            {
                return "";
            }
            else
            {
                return Convert.ToString(HttpContext.Current.Session["TeacherID"]);
            }
        }
    }
    public static string ArticleIdOfFrontShizhi
    {
        get
        {
            return GetSettingValue("ArticleIdOfFrontShizhi").Value;
        }
    }
    public static string ArticleIdOfFrontDongyingqu
    {
        get
        {
            return GetSettingValue("ArticleIdOfFrontDongyingqu").Value;
        }
    }
    public static string ArticleIdOfFrontHekouqu
    {
        get
        {
            return GetSettingValue("ArticleIdOfFrontHekouqu").Value;
        }
    }
    public static string ArticleIdOfFrontKenlixian
    {
        get
        {
            return GetSettingValue("ArticleIdOfFrontKenlixian").Value;
        }
    }
    public static string ArticleIdOfFrontLijinxian
    {
        get
        {
            return GetSettingValue("ArticleIdOfFrontLijinxian").Value;
        }
    }
    public static string ArticleIdOfFrontGuangraoxian
    {
        get
        {
            return GetSettingValue("ArticleIdOfFrontGuangraoxian").Value;
        }
    }
    public static Article ArticleOfIntroduceForDongyingshi
    {
        get
        {
            string aid =  GetSettingValue("ArticleIdOfIntroduceForDongyingshi").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }
    public static Article ArticleOfIntroduceForDongyingqu
    {
        get
        {
            string aid= GetSettingValue("ArticleIdOfIntroduceForDongyingqu").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }
    public static Article ArticleOfIntroduceForHekouqu
    {
        get
        {
            string aid= GetSettingValue("ArticleIdOfIntroduceForHekouqu").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }
    public static Article ArticleOfIntroduceForGuangraoxian
    {
        get
        {
            string aid= GetSettingValue("ArticleIdOfIntroduceForGuangraoxian").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }
    public static Article ArticleOfIntroduceForKenlixian
    {
        get
        {
            string aid= GetSettingValue("ArticleIdOfIntroduceForKenlixian").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }
    public static Article ArticleOfIntroduceForLijinxian
    {
        get
        {
            string aid= GetSettingValue("ArticleIdOfIntroduceForLijinxian").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }
    public static Article ArticleOfIntroduceForDepartment
    {
        get
        {
            string aid = GetSettingValue("ArticleIdOfIntroduceForDepartment").Value;
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.ID == aid select aA;

            if (q.Count() == 0)
            {
                return null;
            }
            else
            {
                return q.First();
            }
        }
    }



    public static string RemoveHtmlTags(string text)
    {
        Regex reg = new Regex("<[^>]+>");
        text = reg.Replace(text, "").Trim();

        reg = new Regex("&[a-zA-Z]+;");
        text = reg.Replace(text, "").Trim();

        reg = new Regex(@"\s+");
        text = reg.Replace(text, "").Trim();

        return text;
    }



    public static Topic GetTopicByName(string name)
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aT in db.Topic where aT.Name == name select aT;

        return q.Count() == 0 ? null : q.First();
    }

    public static Article GetFirstArticleOfTopic(string name)
    {
        Topic topic = GetTopicByName(name);

        if (topic == null)
        {
            return null;
        }
        else
        {
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article where aA.TopicID == topic.ID select aA;

            return q.Count() == 0 ? null : q.First();
        }
    }

    public static string OmitText(string text,int length)
    {
        if (text == null)
        {
            return null;
        }

        text = text.Trim();

        return text.Length > length ? text.Substring(0, length - 2) + "..." : text;
    }
    public static string LongDate(DateTime date)
    {
        return string.Format("{0:yyyy-MM-dd}", date);
    }
    public static string ShortDate(DateTime date)
    {
        return string.Format("{0:MM-dd}", date);
    }

    public static string CreateHyperLink(string root, string path, string url, string target, string title, string text)
    {
        string pattern = "<a href='{0}/{1}/{2}' target='{3}' title='{4}'>{5}</a>";
        string a = string.Format(pattern, root, path, url, target, title, text);
        return a;
    }

    public static string CreateHyperLink(string path, string url, string target, string title, string text)
    {
        string pattern = "<a href='{0}/{1}/{2}' target='{3}' title='{4}'>{5}</a>";
        string a = string.Format(pattern, ApplicationRoot, path, url, target, title, text);
        return a;
    }

    public static string CreateHyperLink(string url, string target, string title, string text)
    {
        string pattern = "<a href='{0}' target='{1}' title='{2}'>{3}</a>";
        string a = string.Format(pattern, ApplicationRoot, url, target, title, text);
        return a;
    }

    public static string CreateHyperLink(string path, string url, string text)
    {
        string pattern = "<a href='{0}/{1}/{2}'>{3}</a>";
        string a = string.Format(pattern, ApplicationRoot, path, url, text);
        return a;
    }


    

    private static Setting GetSettingValue(string key)
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aS in db.Setting
                where aS.SettingKey == key
                select aS;
        if (q.Count() == 0)
        {
            return null;
        }
        else
        {
            return q.First();
        }
    }
    private static List<Setting> GetSettingValues(string key)
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aS in db.Setting
                where aS.SettingKey == key
                select aS;
        if (q.Count() == 0)
        {
            return null;
        }
        else
        {
            return q.ToList();
        }
    }
    public static string GetRealDataFilePath(string file)
        {
            return HttpContext.Current.Server.MapPath("~/Data/" + file);
        }


    public static bool HasPower(Powers power)
    {
        if (HttpContext.Current.Session["ManagerPower"] == null)
        {
            return false;
        }

        int up = Convert.ToInt32(HttpContext.Current.Session["ManagerPower"]);
        if ((up & (int)power) == (int)power)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static bool IsVirtualTeacher
    {
        get{
            if (CurrentTeacherID=="")
            {
                return false;
            }

            CmsDataContext db = new CmsDataContext();
            Teacher teacher = (from aT in db.Teacher
                               where aT.ID == CurrentTeacherID
                               select aT).First();

            return teacher.Courses.Contains("其它");
        }
    }
    public static bool IsChildBelong(string parent, string child)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Toolkit.GetRealDataFilePath("Department.xml"));
        XmlElement root = doc.DocumentElement;

        return root.SelectSingleNode(string.Format("//Depart[@name='{0}']//Depart[@name='{1}']", parent, child)) != null;
    }



    public static void StaticArticle(string filename, string template)
    {
        string folder = HttpContext.Current.Server.MapPath(Toolkit.PathOfArticle);

        #region 创建静态文章目录
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }
        #endregion

        #region 删除已经存在的静态文章
        string path = string.Format("{0}/{1}", folder, filename);
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        #endregion

        string[] ss = filename.Split(new char[] { '/', '.' });
        #region 检查目标文件夹是否存在
        if (!Directory.Exists(string.Format("{0}/{1}", folder, ss[0])))
        {
            Directory.CreateDirectory(string.Format("{0}/{1}", folder, ss[0]));
        }
        if (!Directory.Exists(string.Format("{0}/{1}/{2}", folder, ss[0], ss[1])))
        {
            Directory.CreateDirectory(string.Format("{0}/{1}/{2}", folder, ss[0], ss[1]));
        }
        #endregion

        #region 静态化文章
        TextWriter tw = new StringWriter();
        HttpContext.Current.Server.Execute(string.Format(@"{0}/{1}.aspx?aid={2}", PathOfTemplates, template, ss[2]), tw);

        StreamWriter writer = new StreamWriter(string.Format("{0}/{1}", folder, filename), false, System.Text.Encoding.UTF8);
        writer.Write(tw.ToString().Replace("../", Toolkit.ApplicationRoot + "/"));

        writer.Close();
        tw.Close();
        #endregion
    }

    public static string EncryptPassword(string password)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] fromData = System.Text.Encoding.Unicode.GetBytes(password);
        byte[] targetData = md5.ComputeHash(fromData);
        string byte2String = null;

        for (int i = 0; i < targetData.Length; i++)
        {
            byte2String += targetData[i].ToString("x");
        }

        return byte2String;
    }

    public static string MappingPath(string path)
    {
        return HttpContext.Current.Server.MapPath(path);
    }
}